package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.admin.entity.AdUser;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.util.JwtUtils;
import com.usian.model.admin.dtos.AdUserLoginDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-09-29
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Map<String, Object> login(AdUserLoginDto dto) {
        //1、参数校验
        if(dto==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2、根据用户名查询用户是否存在
        QueryWrapper<AdUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AdUser::getName,dto.getName());
        AdUser adUser = this.getOne(queryWrapper);
        if(adUser==null){
            throw new LeadException(AppHttpCodeEnum.LOGIN_USERNAME_ERROR);
        }
        //3、校验密码是否正确
        boolean matches = passwordEncoder.matches(dto.getPassword(), adUser.getPassword());
        if(!matches){
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //4、生成token
        String token = JwtUtils.generateTokenExpireInMinutes(adUser.getId(), 60);

        //5、组装返回的结果
        Map<String,Object> map = new HashMap<>();
        adUser.setPassword("");
        adUser.setEmail("");
        map.put("token",token);
        map.put("user",adUser);
        return map;
    }
}
